#!/usr/bin/env lua

local appName          = "internet-detector"
local appExec          = "/usr/bin/internet-detector"
local mailsendExec     = "/usr/bin/mailsend"
local modemManagerInit = "/etc/init.d/modemmanager"
local curlExec         = "/usr/bin/curl"

local InternetDetector = require(appName .. ".main")
local uci              = require("uci")
local unistd           = require("posix.unistd")

local function prequire(package)
	local retVal, pkg = pcall(require, package)
	return retVal and pkg
end

local function init()
	local lines = {}
	if prequire(appName .. ".modules.mod_modem_restart") then
		lines[#lines + 1] = '"mm_mod":true'
		if (unistd.access(modemManagerInit, "x") and
			os.execute(modemManagerInit .. " enabled") == 0) then
			lines[#lines + 1] = '"mm_init":true'
		else
			lines[#lines + 1] = '"mm_init":false'
		end
	else
		lines[#lines + 1] = '"mm_mod":false'
	end
	if prequire(appName .. ".modules.mod_email") then
		lines[#lines + 1] = '"email_mod":true'
		if unistd.access(mailsendExec, "x") then
			lines[#lines + 1] = '"email_exec":true'
		else
			lines[#lines + 1] = '"email_exec":false'
		end
	else
		lines[#lines + 1] = '"email_mod":false'
	end
	if prequire(appName .. ".modules.mod_telegram") then
		lines[#lines + 1] = '"telegram":true'
	else
		lines[#lines + 1] = '"telegram":false'
	end
	if unistd.access(curlExec, "x") then
		lines[#lines + 1] = '"curl_exec":true'
	else
		lines[#lines + 1] = '"curl_exec":false'
	end
	return string.format("{%s}", table.concat(lines, ","))
end

local function startUiInstances()
	local uciCursor = uci.cursor()
	local mode      = tonumber(uciCursor:get(appName, "config", "mode"))
	if mode == 2 then
		uciCursor:foreach(
			appName,
			"instance",
			function(s)
				if s.enabled == "1" then
					os.execute(string.format("%s -a daemon -i %s", appExec, s[".name"]))
				end
			end
		)
	end
end

local function uiPoll()
	if InternetDetector:status() == "stoped" then
		startUiInstances()
	else
		InternetDetector:setSIGUSR()
	end
	return InternetDetector:inetStatus()
end

local function list()
	io.write('{"Init":{},"Status":{},"InetStatus":{},"UIPoll":{}}')
end

if arg[1] == "list" then
	list()
elseif arg[1] == "call" then
	if arg[2] == "Init" then
		io.write(init())
	elseif arg[2] == "Status" then
		io.write(string.format('{"status":"%s"}', tostring(InternetDetector:status())))
	elseif arg[2] == "InetStatus" then
		io.write(InternetDetector:inetStatus())
	elseif arg[2] == "UIPoll" then
		io.write(uiPoll())
	end
end

os.exit(0)
